// 视图
import view from '@src/views/admin';
// 组件
import adminListComponent from '@src/components/adminList'
// 弹窗工具
import toastr from 'toastr';
import Swal from 'sweetalert2'
// api
import * as adminApi from '@src/api/admin';
// util
import checkUtil from '@src/util/checkUtil';

// 渲染
const render = () => {
  adminApi.list()
    .then(res => {
      document.querySelector("#amdinListBox").innerHTML = adminListComponent({
        list: res.data
      });
    });
};

// 新增
const add = () => {
  const account = document.adminForm.account.value.trim()
  const pwd = document.adminForm.pwd.value.trim()
  const pwd2 = document.adminForm.pwd2.value.trim()

  if (!checkUtil.checkAccount(account)) {
    return;
  }

  if (!checkUtil.checkPwd(pwd)) {
    return;
  }

  if (pwd !== pwd2) {
    toastr.error('两次输入的密码不一致');
    return;
  }

  // 新增
  adminApi.add(account, pwd)
    .then(() => {
      toastr.success("添加管理员成功");
      // 关闭模态框
      $('#addAdminModal').modal('hide');
      // 清空表单
      document.adminForm.reset();
      // 重新渲染页面
      render();
    });






}

// 删除
const del = ({ target }) => {
  if (!target.classList.contains('deleteAdminBtn')) {
    return;
  }
  Swal.fire({
    title: "确定删除？",
    text: "删除数据后无法恢复",
    icon: "warning",
    showCancelButton: true,
    confirmButtonColor: "#3085d6",
    cancelButtonColor: "#d33",
    confirmButtonText: "确定",
    cancelButtonText: "取消",
  }).then((result) => {
    if (!result.isConfirmed) {
      return;
    }
    adminApi.del(target.dataset.id)
      .then(() => {
        toastr.success('删除成功');
        // 重新渲染页面
        render();
      });
  })
};


export default (req, res, next) => {
  // 渲染页面
  res.render(
    view()
  );

  // 渲染列表
  render();

  // 监听新增
  document.querySelector("#addAdminBtn").addEventListener('click', add)

  // 监听删除
  document.querySelector('#amdinListBox').addEventListener('click', del)
}